package com.xc58.highreactor.seril;

import static com.xc58.highreactor.util.ByteUtil.toInt;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.LinkedList;

import com.xc58.highreactor.exception.ParseDataException;

import static com.xc58.highreactor.util.ByteUtil.*;

@SuppressWarnings({"rawtypes","unchecked"})
public class LinkedListSerializer implements ISerializer<LinkedList>{
	private static final byte[] ZERO = new byte[]{0,0,0,0};
	public byte[] serialize(LinkedList rawObject) throws Exception {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int length = rawObject.size();
		out.write(getByteFormInt(length));
		Iterator i = rawObject.iterator();
		while(i.hasNext()){
			Object cur = i.next();
			if(cur == null){
				out.write(ZERO);
				continue;
			}
			int type = SerialMatcher.getClassFlag(cur.getClass());
			byte[] serial = SerialMatcher.serializer(type, cur);
			out.write(getByteFormInt(type));
			out.write(serial);
		}
		byte[] result = out.toByteArray();
		out.close();
		return result;
	}

	public LinkedList deserialize(InputStream input) throws Exception {
		
		LinkedList list = new LinkedList();
		int length = 0;
		byte[] blength = new byte[4];
		if(input.read(blength) < 4){
			throw new ParseDataException();
		}
		length = toInt(blength);
		
		for (int i = 0; i < length; i++) {
			byte[] btype = new byte[4];
			input.read(btype);
			int type = toInt(btype);
			if(type == 0){
				list.add(null);
				continue;
			}
			Object cur = SerialMatcher.deserializer(type,input);
			list.add(cur);
		}
		return list;
	}
}
